<%page args="course_overview, enrollment, entitlement, entitlement_session, course_card_index, enrollments_fbe_is_on, is_unfulfilled_entitlement, is_fulfilled_entitlement, entitlement_available_sessions, entitlement_expiration_date, entitlement_expired_at, show_courseware_link, cert_status, can_refund_entitlement, can_unenroll, credit_status, show_email_settings, course_mode_info, is_paid_course, is_course_voucher_refundable, course_requirements, dashboard_index, share_settings, related_programs, display_course_modes_on_dashboard, show_consent_link, enterprise_customer_name, resume_button_url, partner_managed_enrollment" expression_filter="h"/>

<%!
import datetime

from django.conf import settings
from django.utils.http import urlencode
from urllib.parse import quote_plus
from django.utils.translation import gettext as _
from django.utils.translation import ngettext
from django.urls import reverse
from common.djangoapps.course_modes.models import CourseMode
from common.djangoapps.course_modes.helpers import enrollment_mode_display
from common.djangoapps.student.helpers import user_has_passing_grade_in_course
from lms.djangoapps.verify_student.services import IDVerificationService
from openedx.core.djangolib.js_utils import dump_js_escaped_json, js_escaped_string
from openedx.core.djangolib.markup import HTML, Text
from openedx.features.course_experience import course_home_url
from common.djangoapps.student.helpers import (
  VERIFY_STATUS_NEED_TO_VERIFY,
  VERIFY_STATUS_SUBMITTED,
  VERIFY_STATUS_RESUBMITTED,
  VERIFY_STATUS_APPROVED,
  VERIFY_STATUS_MISSED_DEADLINE,
  VERIFY_STATUS_NEED_TO_REVERIFY,
  DISABLE_UNENROLL_CERT_STATES,
)
from common.djangoapps.util.course import get_link_for_about_page, get_encoded_course_sharing_utm_params
from lms.djangoapps.experiments.utils import UPSELL_TRACKING_FLAG
%>

<%
  reverify_link = IDVerificationService.get_verify_location()
  cert_name_short = course_overview.cert_name_short
  if cert_name_short == "":
    cert_name_short = settings.CERT_NAME_SHORT

  cert_name_long = course_overview.cert_name_long
  if cert_name_long == "":
    cert_name_long = settings.CERT_NAME_LONG

  is_course_expired = hasattr(show_courseware_link, 'error_code') and show_courseware_link.error_code == 'audit_expired'

  display_course_upgrade = (
      use_ecommerce_payment_flow
      and course_mode_info
      and course_mode_info['show_upsell']
      and not entitlement
      and course_mode_info['verified_sku']
  )
%>

<%
  is_non_certificate_enrollment = enrollment.mode == "audit" or enrollment.mode == "honor"
  is_passing_course = user_has_passing_grade_in_course(enrollment)
  course_ended_not_passing = course_overview.has_ended() and is_passing_course == False and is_non_certificate_enrollment == False
%>

<%namespace name='static' file='../static_content.html'/>

<li class="course-item">
  % if display_course_modes_on_dashboard:
    <%
        course_verified_certs = enrollment_mode_display(
            enrollment.mode,
            course_overview.id
        )
    %>
    <%
        mode_class = course_verified_certs.get('display_mode', '')
        if mode_class:
            mode_class = ' ' + mode_class ;
    %>
  % else:
    <% mode_class = '' %>
  % endif
      <div class="course-container"
        % if getattr(course_overview, 'language'):
          lang="${course_overview.language}"
        % endif
      >
<article class="course${mode_class}" aria-labelledby="course-title-${enrollment.course_id}" id="course-card-${course_card_index}">
  <% course_target = course_home_url(course_overview.id) %>
  <section class="details" aria-labelledby="details-heading-${enrollment.course_id}">
      <h2 class="hd hd-2 sr" id="details-heading-${enrollment.course_id}">${_('Course details')}</h2>
    <div class="wrapper-course-image" aria-hidden="true">
      % if show_courseware_link and not is_unfulfilled_entitlement:
        % if not is_course_expired:
            <a href="${course_target}" data-course-key="${enrollment.course_id}" class="cover course-target-link" tabindex="-1">
              <img src="${course_overview.image_urls['small']}" class="course-image" alt="${_('{course_number} {course_name} Home Page').format(course_number=course_overview.number, course_name=course_overview.display_name_with_default)}" />
            </a>
        % else:
            <a class="fade-cover">
              <img src="${course_overview.image_urls['small']}" class="course-image" alt="${_('{course_number} {course_name} Cover Image').format(course_number=course_overview.number, course_name=course_overview.display_name_with_default)}" />
            </a>
        % endif
      % else:
        <a class="cover">
          <img src="${course_overview.image_urls['small']}" class="course-image" alt="${_('{course_number} {course_name} Cover Image').format(course_number=course_overview.number, course_name=course_overview.display_name_with_default)}" />
        </a>
      % endif
      % if display_course_modes_on_dashboard and course_verified_certs.get('display_mode') != 'audit':
        <span class="sts-enrollment" title="${course_verified_certs.get('enrollment_title')}">
          <span class="label">${_("Enrolled as: ")}</span>
          % if course_verified_certs.get('show_image'):
              <img class="deco-graphic" src="${static.url('images/verified-ribbon.png')}" alt="${course_verified_certs.get('image_alt')}" />
          % endif
          <div class="sts-enrollment-value">${course_verified_certs.get('enrollment_value')}</div>
        </span>
      % endif
    </div>
      <div class="wrapper-course-details">
        <h3 class="course-title" id="course-title-${enrollment.course_id}">
          % if show_courseware_link and not is_unfulfilled_entitlement:
            % if not is_course_expired:
              <a data-course-key="${enrollment.course_id}" href="${course_target}" class="course-target-link">${course_overview.display_name_with_default}</a>
            % else:
              <a class="disable-look" data-course-key="${enrollment.course_id}">${course_overview.display_name_with_default}</a>
            % endif
          % else:
            <span>${course_overview.display_name_with_default}</span>
          % endif
        </h3>
        <div class="wrapper-course-info-actions">
          <div class="wrapper-course-info-row">
            <div class="course-info">
              <span class="info-university">${course_overview.display_org_with_default} - </span>
              <span class="info-course-id">${course_overview.display_number_with_default}</span>
              <%
                enrollment_date = course_overview.self_paced and enrollment and enrollment.created
                if course_overview.start_date_is_still_default:
                    container_string = _("Coming Soon")
                    course_date = None
                else:
                    format = 'shortDate'
                    dashboard_start_display = course_overview.dashboard_start_display
                    if course_overview.has_ended():
                        container_string = _("Ended - {date}")
                        course_date = course_overview.end
                    elif course_overview.has_started():
                        container_string = _("Started - {date}")
                        if enrollment_date and isinstance(dashboard_start_display, datetime.datetime):
                          course_date = max(enrollment_date, dashboard_start_display)
                        else:
                          course_date = enrollment_date or dashboard_start_display
                    elif course_overview.starts_within(days=5):
                        container_string = _("Starts - {date}")
                        course_date = dashboard_start_display
                        format = 'defaultFormat'
                    else: ## hasn't started yet
                        container_string = _("Starts - {date}")
                        course_date = dashboard_start_display
                    endif
                endif
              %>

                <span class="info-date-block-container">
                    % if not is_unfulfilled_entitlement and is_course_expired:
                      <span class="info-date-block" data-course-key="${enrollment.course_id}">
                        ${show_courseware_link.user_message}
                        <span class="sr">
                          &nbsp;${_('for {course_display_name}').format(course_display_name=course_overview.display_name_with_default)}
                        </span>
                      </span>
                    % elif is_unfulfilled_entitlement:
                        <span class="info-date-block" aria-live="polite">
                            <span class="icon fa fa-warning" aria-hidden="true"></span>
                            % if not entitlement_expired_at:
                                % if entitlement_expiration_date:
                                    ${_('You must select a session by {expiration_date} to access the course.').format(expiration_date=entitlement_expiration_date)}
                                % else:
                                    ${_('You must select a session to access the course.')}
                                % endif
                            % endif
                        </span>
                    % else:
                        % if isinstance(course_date, str):
                            <span class="info-date-block">${container_string.format(date=course_date)}</span>
                        % elif course_date is not None:
                            <span class="info-date-block localized-datetime" data-language="${user_language}" data-timezone="${user_timezone}" data-datetime="${course_date.strftime('%Y-%m-%dT%H:%M:%S%z')}" data-format=${format} data-string="${container_string}"></span>
                        % endif
                    % endif
                    % if entitlement:
                        % if not entitlement_expired_at:
                            <button class="change-session btn-link ${'hidden' if is_unfulfilled_entitlement else ''}">${_('Change or Leave Session')}</button>
                        % endif
                    % endif
                </span>
                % if entitlement and not is_unfulfilled_entitlement and entitlement_expiration_date:
                    <div class="info-expires-at">
                            <span class="msg-icon fa fa-warning" aria-hidden="true"></span>
                            % if entitlement_expired_at:
                                ${_('You can no longer change sessions.')}
                            % else:
                                ${_('You can change sessions until {entitlement_expiration_date}.').format(entitlement_expiration_date=entitlement_expiration_date)}
                            % endif
                    </div>
                % endif
            </div>
            <div class="wrapper-course-actions">
              <div class="course-actions">
                % if show_courseware_link or course_overview.has_social_sharing_url() or course_overview.has_marketing_url():
                    % if share_settings:
                        <%
                          share_url = get_link_for_about_page(course_overview)
                          encoded_utm_parameters = get_encoded_course_sharing_utm_params()
                          share_window_name = 'shareWindow'
                          share_window_config = 'toolbar=no, location=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=640, height=480'
                        %>
                        % if share_settings.get('DASHBOARD_FACEBOOK', False):
                            <%
                              facebook_share_url = u"{url}?{utm_params}".format(url=share_url, utm_params=encoded_utm_parameters['facebook'])
                              share_text = _("I'm taking {course_name} online with {facebook_brand}. Check it out!").format(course_name=course_overview.display_name_with_default, facebook_brand=share_settings.get('FACEBOOK_BRAND', 'edX.org'))
                              query_params = urlencode((('u', facebook_share_url), ('quote', share_text),))
                              facebook_url = 'https://www.facebook.com/sharer/sharer.php?{query}'.format(query=query_params)
                              share_msg = _("Share {course_name} on Facebook").format(course_name=course_overview.display_name_with_default)
                            %>
                            <a
                              data-tooltip="${_('Share on Facebook')}"
                              data-trigger="focus hover"
                              class="action action-facebook"
                              href="${facebook_url}"
                              rel="noopener"
                              target="_blank"
                              title="${_('Share on Facebook')}"
                              data-course-id="${course_overview.id}"
                              onclick="var popupWindow = window.open('${facebook_url}', '${share_window_name}', '${share_window_config}'); popupWindow.opener = null; return false;">
                              <span class="sr">${share_msg}</span>
                              <span class="fa fa-facebook" aria-hidden="true"></span>
                            </a>
                        % endif
                        % if share_settings.get('DASHBOARD_TWITTER', False):
                            <%
                              twitter_share_url = u"{url}?{utm_params}".format(url=share_url, utm_params=encoded_utm_parameters['twitter'])
                              default_share_text = _("I'm taking {course_name} online with {twitter_brand}. Check it out!").format(course_name=course_overview.display_name_with_default, twitter_brand=share_settings.get('TWITTER_BRAND', '@edxonline'))
                              share_text = quote_plus(share_settings.get('DASHBOARD_TWITTER_TEXT', default_share_text))
                              twitter_url = u'https://twitter.com/intent/tweet?text=' + share_text + u'%20' + quote_plus(twitter_share_url)
                              share_msg = _("Share {course_name} on Twitter").format(course_name=course_overview.display_name_with_default)
                            %>
                            <a
                              data-tooltip="${_('Share on Twitter')}"
                              data-trigger="focus hover"
                              class="action action-twitter"
                              href="${twitter_url}"
                              rel="noopener"
                              target="_blank"
                              title="${_('Share on Twitter')}"
                              data-course-id="${course_overview.id}"
                              onclick="var popupWindow = window.open('${twitter_url}', '${share_window_name}', '${share_window_config}'); popupWindow.opener = null; return false;">
                              <span class="sr">${share_msg}</span>
                              <span class="fa fa-twitter" aria-hidden="true"></span>
                            </a>
                        % endif
                    % endif
                % endif

                ## We should only show the gear dropdown if the user is able to refund/unenroll from their entitlement
                ## and/or if they have selected a course run, unenrollment is not disabled, and email_settings are enabled
                ## as these are the only actions currently available
                % if entitlement and (can_refund_entitlement or show_email_settings):
                    <%include file='_dashboard_entitlement_actions.html' args='course_overview=course_overview,entitlement=entitlement,dashboard_index=dashboard_index, can_refund_entitlement=can_refund_entitlement, show_email_settings=show_email_settings'/>
                % elif not entitlement and (can_unenroll or partner_managed_enrollment or show_email_settings):
                    <div class="wrapper-action-more" data-course-key="${enrollment.course_id}">
                      <button type="button" class="action action-more" id="actions-dropdown-link-${dashboard_index}" aria-haspopup="true" aria-expanded="false" aria-controls="actions-dropdown-${dashboard_index}" data-course-number="${course_overview.number}" data-course-name="${course_overview.display_name_with_default}" data-dashboard-index="${dashboard_index}">
                        <span class="sr">${_('Course options for')}</span>
                        <span class="sr">&nbsp;
                          ${course_overview.display_name_with_default}
                        </span>
                        <span class="fa fa-cog" aria-hidden="true"></span>
                      </button>
                      <div class="actions-dropdown" id="actions-dropdown-${dashboard_index}" tabindex="-1">
                        <ul class="actions-dropdown-list" id="actions-dropdown-list-${dashboard_index}" aria-label="${_('Available Actions')}" role="menu">
                          % if can_unenroll:
                            <li class="actions-item" id="actions-item-unenroll-${dashboard_index}" role="menuitem">
                              <% course_refund_url = reverse('course_run_refund_status', args=[str(course_overview.id)]) %>
                                  <a href="#unenroll-modal" class="action action-unenroll" rel="leanModal"
                                    data-course-id="${course_overview.id}"
                                    data-course-number="${course_overview.number}"
                                    data-course-name="${course_overview.display_name_with_default}"
                                    data-dashboard-index="${dashboard_index}"
                                    data-course-refund-url="${course_refund_url}"
                                    data-course-is-paid-course="${is_paid_course}"
                                    data-is-course-voucher-refundable="${is_course_voucher_refundable}"
                                    data-course-cert-name-long="${cert_name_long}"
                                    data-course-enrollment-mode="${enrollment.mode}">
                                    ${_('Unenroll')}
                                  </a>
                            </li>
                        % elif partner_managed_enrollment:
                          <li class="actions-item" id="actions-item-enrolled-by-partner-${dashboard_index}" role="menuitem">
                            <a class="action action-message action-unenroll-managed-enrollment">
                              ${_('You are enrolled by your institution and you should reach out to your institution to drop this course.')}
                            </a>
                          </li>
                        % endif
                          <li class="actions-item" id="actions-item-email-settings-${dashboard_index}" role="menuitem">
                            % if show_email_settings:
                                <a href="#email-settings-modal" class="action action-email-settings" rel="leanModal" data-course-id="${course_overview.id}" data-course-number="${course_overview.number}" data-dashboard-index="${dashboard_index}" data-optout="${course_overview.id in course_optouts}">${_('Email Settings')}</a>
                            % endif
                          </li>
                        </ul>
                      </div>
                    </div>
                % endif
              </div>
            </div>
          </div>

          <div class="continue-button">
              % if (show_courseware_link or is_unfulfilled_entitlement) and not is_course_expired:
                % if course_overview.has_ended():
                  % if not is_unfulfilled_entitlement:
                    <a href="${course_target}" class="enter-course archived course-target-link" data-course-key="${enrollment.course_id}">${_('View Archived Course')}<span class="sr">&nbsp;${course_overview.display_name_with_default}</span></a>
                  % endif

                % else:
                  <%include file="_dashboard_course_resume.html" args="resume_button_url=resume_button_url, course_overview=course_overview, enrollment=enrollment, is_unfulfilled_entitlement=is_unfulfilled_entitlement, course_target=course_target, related_programs=related_programs"/>
                % endif
              % endif
          </div>
        </div>
      </div>
  </section>
  <footer class="wrapper-messages-primary">
    <div class="messages-list">

      % if entitlement and not entitlement_expired_at:
        <div class="course-entitlement-selection-container ${'' if is_unfulfilled_entitlement else 'hidden'}"></div>
        <%static:webpack entry="EntitlementFactory">
          EntitlementFactory({
              el: '${ '#course-card-' + str(course_card_index) + ' .course-entitlement-selection-container' | n, js_escaped_string }',
              triggerOpenBtn: '${ '#course-card-' + str(course_card_index) + ' .change-session' | n, js_escaped_string }',
              courseCardMessages: '${ '#course-card-' + str(course_card_index) + ' .messages-list > .message' | n, js_escaped_string }',
              courseTitleLink: '${ '#course-card-' + str(course_card_index) + ' .course-title a' | n, js_escaped_string }',
              courseImageLink: '${ '#course-card-' + str(course_card_index) + ' .wrapper-course-image > a' | n, js_escaped_string }',
              dateDisplayField: '${ '#course-card-' + str(course_card_index) + ' .info-date-block' | n, js_escaped_string }',
              policyMsg: '${ '#course-card-' + str(course_card_index) + ' .info-expires-at' | n, js_escaped_string }',
              enterCourseBtn: '${ '#course-card-' + str(course_card_index) + ' .enter-course' | n, js_escaped_string }',
              availableSessions: '${ entitlement_available_sessions | n, dump_js_escaped_json }',
              entitlementUUID: '${ entitlement.course_uuid | n, js_escaped_string }',
              currentSessionId: '${ entitlement_session.course_id if entitlement_session else "" | n, js_escaped_string }',
              enrollUrl: '${ reverse('entitlements_api:v1:enrollments', args=[str(entitlement.uuid)]) | n, js_escaped_string }',
              courseHomeUrl: '${ course_target | n, js_escaped_string }',
              expiredAt: '${ entitlement.expired_at_datetime | n, js_escaped_string }',
              daysUntilExpiration: '${ entitlement.get_days_until_expiration() | n, js_escaped_string }'
          });
        </%static:webpack>
      %endif

      % if related_programs:
        <div class="message message-related-programs is-shown">
          <span class="related-programs-preface" tabindex="0">${_('Related Programs')}:</span>
          <ul class="related-program-container" >
            % for program in related_programs:
              ## intentionally using multiple classnames here to bump up specificity
            <li class="related-program-element important-element">
              <span class="category-icon ${program['type'].lower()}-icon" aria-hidden="true"></span>
              <span><a href="${program['detail_url']}">${u'{title} {type}'.format(title=program['title'], type=program['type'])}</a></span>
            </li>
            % endfor
          </ul>
        </div>
      % endif

      % if cert_status:
        <%include file='_dashboard_certificate_information.html' args='cert_status=cert_status, course_ended_not_passing=course_ended_not_passing, course_overview=course_overview, enrollment=enrollment, reverify_link=reverify_link'/>
      % endif

      % if credit_status is not None:
        <%include file="_dashboard_credit_info.html" args="credit_status=credit_status"/>
      % endif

        % if show_consent_link:
          <%include file="_dashboard_show_consent.html" args="course_overview=course_overview, course_target=course_target, enrollment=enrollment, enterprise_customer_name=enterprise_customer_name"/>
        %endif

        % if display_course_upgrade:
          <div class="message message-upsell has-actions is-shown">
            <div class="wrapper-extended">
              <div class="wrapper-icon-message">
                <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="" aria-hidden="true" focusable="false">
                  <path d="M19 5h-2V3H7v2H5c-1.1 0-2 .9-2 2v1c0 2.55 1.92 4.63 4.39 4.94A5.01 5.01 0 0011 15.9V19H7v2h10v-2h-4v-3.1a5.01 5.01 0 003.61-2.96C19.08 12.63 21 10.55 21 8V7c0-1.1-.9-2-2-2zM5 8V7h2v3.82C5.84 10.4 5 9.3 5 8zm14 0c0 1.3-.84 2.4-2 2.82V7h2v1z" fill="currentColor"></path>
                </svg>
                <div class="message-copy" align="auto">
                % if enrollment.course_id in enrollments_fbe_is_on:
                  ${Text(_("{start_bold}Get the most out of your course!{end_bold} Upgrade to get full access to the course material, unlock both graded and non-graded assignments, and earn a {link_start}verified certificate{link_end} to showcase on your resumé.")).format(
                          start_bold=HTML('<strong class="message-copy-bold">'),
                          end_bold=HTML('</strong>'),
                          link_start=HTML('<a href="{}" class="verified-info" data-course-key="{}">').format(
                            marketing_link('WHAT_IS_VERIFIED_CERT'),
                            enrollment.course_id
                          ),
                          link_end=HTML('</a>')
                        )}
                % else:
                  ${Text(_("{start_bold}Get the most out of your course!{end_bold} Upgrade to earn a {link_start}verified certificate{link_end} to showcase on your resumé.")).format(
                          start_bold=HTML('<strong class="message-copy-bold">'),
                          end_bold=HTML('</strong>'),
                          link_start=HTML('<a href="{}" class="verified-info" data-course-key="{}">').format(
                            marketing_link('WHAT_IS_VERIFIED_CERT'),
                            enrollment.course_id
                          ),
                          link_end=HTML('</a>')
                        )}
                % endif
                </div>
              </div>
              <div class="action-upgrade-container">
                <a class="action action-upgrade track_course_dashboard_green_button" href="${ecommerce_payment_page}?sku=${course_mode_info['verified_sku']}">
                  <span class="wrapper-copy">
                    <span class="copy" id="upgrade-to-verified">${_("Upgrade")}</span>
                      <span class="sr">&nbsp;${_(course_overview.display_name_with_default)}</span>
                  </span>
                </a>
              </div>
            </div>
          </div>
        % endif

        % if course_requirements:
        ## Multiple pre-requisite courses are not supported on frontend that's why we are pulling first element
        <% prc_target = reverse('about_course', args=[str(course_requirements['courses'][0]['key'])]) %>
        <div class="prerequisites">
          <p class="tip">
            ${Text(_("You must successfully complete {link_start}{prc_display}{link_end} before you begin this course.")).format(
                link_start=HTML('<a href="{}">').format(prc_target),
                link_end=HTML('</a>'),
                prc_display=course_requirements['courses'][0]['display'],
              )}
          </p>
        </div>
        % endif
    </div>
  </footer>
</article>
</div>
</li>

% if share_settings.get('DASHBOARD_FACEBOOK', False) and share_settings.get('DASHBOARD_TWITTER', False):
    <%static:require_module_async module_name="js/course_sharing/course_sharing_events" class_name="CourseSharingEvents">
        CourseSharingEvents("${course_overview.id | n, js_escaped_string}");
    </%static:require_module_async>
%endif

<%static:require_module_async module_name="js/dateutil_factory" class_name="DateUtilFactory">
    DateUtilFactory.transform(iterationKey=".localized-datetime");
</%static:require_module_async>

% if UPSELL_TRACKING_FLAG.is_enabled():
    <%static:require_module_async module_name="js/commerce/track_ecommerce_events" class_name="TrackECommerceEvents">
      if (window.loadedECommerceEvents === undefined) {
        window.loadedECommerceEvents = true;

        TrackECommerceEvents.trackUpsellClick($(".track_course_dashboard_green_button"), 'course_dashboard_green', {
          pageName: "course_dashboard",
          linkType: "button",
          linkCategory: "green_upgrade"
        });
      }

    </%static:require_module_async>
%endif
